﻿using ConfExpert.Forms.Base;
using ConfExpert.Properties;
using ConfExpert.Utility;

using DevExpress.Utils;
using DevExpress.XtraEditors.Repository;
using DevExpress.XtraGrid.Views.Grid;
using DevExpress.XtraReports.UI;
using DevExpress.XtraVerticalGrid.Events;
using DevExpress.XtraVerticalGrid.Rows;
using DevTeam;


using System;
using System.Data;
using System.Drawing;
using System.Windows.Forms;

namespace ConfExpert.Forms.Depo.Cikis
{
    public partial class ParcaCikisEmirleri : XForm
    {
        BindingSource bsCE;
        BindingSource bsCELines;

        public int ParcaCikisEmriId
        {
            get
            {
                if (gv.FocusedRowHandle < 0)
                    return -1;
                else
                    return Convert.ToInt32(gv.GetFocusedRowCellValue("ParcaCikisEmriId"));
            }
        }

        public ParcaCikisEmirleri()
        {
            InitializeComponent();
        }

        private void KucukParcaTalepleri_Load(object sender, EventArgs e)
        {
            
            bsCE = gv.Init("GetParcaCikisEmriFiltered", "AÇIK", 0, 0, 0, 0, new DateTime(2000, 1, 1), new DateTime(2000, 1, 1), string.Empty, 0, 0, 0, 0);
            bsCELines = gv.AddDetailGrid(gvLines, "ParcaCikisEmriId");
            //bsCELines2 = gvLines.AddDetailGrid(gvCELines2, "ParcaCikisEmriId,ProductId");

            //Grid e expression içeren sütun ekleme ;
            //{FK} geçen yere fonksiyon otomatik olarak ilk FK nın ismini yazıyor.            
            //gvCELines2.SutunEkle("SelectedQty", typeof(int), "Iif(ISNULL(KesilecekMiktar,0)=0, Qty,ISNULL(KesilecekMiktar,0))");
            //gv.SutunEkle("Qty", typeof(int), "SUM(Child({FK}).Qty)");
            gvLines.AddColumn("KalanAdet", typeof(int), "Iif(ISNULL(stCikisId,2)=2, 1, 0)");

            gv.AddColumn("KalanAdet", typeof(int), "SUM(Child({FK}).KalanAdet)");
            gv.Columns["KalanAdet"].DisplayFormat.FormatType = DevExpress.Utils.FormatType.Numeric;
            gv.Columns["KalanAdet"].DisplayFormat.FormatString = "#,###";
            gv.AddColumn("ToCut", typeof(int), "SUM(Child({FK}).ToCut)");

            //Devx MakeColumnVisible eklemiş, invisible ını da ben ekledim :)
            gv.MakeColumnInvisible("Seç", "ToCut");
            gv.SetCaptions("ParcaCikisEmriId:ParcaId");
            gvLines.MakeColumnInvisible("ParcaCikisEmriId", "Hit", "KalanAdet", "ToCut");

            gv.FormatAsNumber(1, "Miktar");
            gv.FormatAsDateTime("OlusturulmaTarihi");
            gv.Columns["Miktar"].DisplayFormat.FormatString = "#,##0.0;-#,##0.0;";

            gvLines.FormatAsNumber(2, "Miktar2");
            gvLines.Columns["Miktar2"].DisplayFormat.FormatString = "#,##0.00;-#,##0.00;";

            gvLines.FormatAsNumber(1, "CurrentQty");
            gv.AddSummary("KalanAdet");

            if (ytk(97))
            {
                //gm.GridMenu.AddMenu("Topların Yerini Göster", ToplarinYeriniGoster);
                //gm.GridMenu.AddMenu("Kapat", Kapat);
                GridManager gm = GridManager.GetManager(gv);
                gm.GridMenu.AddMenu("Çıkıldı", CikildiA, Resources.ok2);
                gm.GridMenu.AddMenu("Çıkılmadı", CikilmadiA, Resources.delete_16);
                gm.GridMenu.AddMenu("Çeki Listesi", PrintRollCut, null, true);
                gm.GridMenu.AddMenu("Parça etiketi bas", ParcaEtiketiBas);
                gm.GridMenu.AddMenu("İrsaliye yazdır", PrintShip);
                if (ytk(201))
                    gm.GridMenu.AddMenu("İptal Et", IptalEt);

                gm = GridManager.GetManager(gvLines);
                gm.GridMenu.AddMenu("Çıkıldı", Cikildi, Resources.ok2);
                gm.GridMenu.AddMenu("Çıkılmadı", Cikilmadi, Resources.delete_16);

                bbiKaydet.ItemClick += bbiKaydet_ItemClick;
            }
            else
                bbiKaydet.Visibility = DevExpress.XtraBars.BarItemVisibility.Never;


            gv.OptionsBehavior.Editable = gvLines.OptionsBehavior.Editable = false;
            gv.FocusedRowChanged += new DevExpress.XtraGrid.Views.Base.FocusedRowChangedEventHandler(gvCikisEmirleri_FocusedRowChanged);
            gv.RowStyle += new DevExpress.XtraGrid.Views.Grid.RowStyleEventHandler(gvCikisEmirleri_RowStyle);

            this.Text = "Parça Çıkış Emirleri";

            gv.OptionsBehavior.Editable = false;

            splitContainerControl2.AutoSize();


            btnGetir.Click += new EventHandler(btnGetir_Click);
            btnTemizle.Click += new EventHandler(btnTemizle_Click);

            CreateVerticalGrid();

            gv.BestFitColumns();
            gvLines.BestFitColumns();

            gvLines.RowStyle += new RowStyleEventHandler(gvLines_RowStyle);
            gvLines.OptionsView.AllowCellMerge = gvLines.OptionsView.EnableAppearanceEvenRow = false;

        }

        void gvLines_RowStyle(object sender, DevExpress.XtraGrid.Views.Grid.RowStyleEventArgs e)
        {
            if (intParse(((GridView)sender).GetRowCellValue(e.RowHandle, "stCikisId")) == 1)
                e.Appearance.BackColor = Color.LightBlue;
        }


        void bbiKaydet_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            bsCELines.EndEdit();

            DataTable dt = new DataTable("Toplar");
            dt.Columns.Add("ParcaCikisEmriId", typeof(int));
            dt.Columns.Add("RollId", typeof(int));

            foreach (DataRow dr in gvLines.DataTable().Select("stCikisId=1"))
                dt.Rows.Add((int)dr["ParcaCikisEmriId"], (int)dr["RollId"]);

            string str = dt.SerializeChanges();
            //string Message = gvLines.GetChangesAsXml("ParcaCikisEmriLines");
            if (str != string.Empty)
            {
                ExecuteNonQuery("UpdParcaCikis", str, WhoAmI);
                Yenile();
            }
        }



        void CikildiA(object sender, EventArgs e)
        {
            foreach (int handle in gv.GetSelectedRows())
                if (intParse(gv.GetRowCellValue(handle, "stGenelId")) < 2)
                    foreach (DataRow dr in gvLines.DataTable().Select("ParcaCikisEmriId=" + strParse(gv.GetRowCellValue(handle, "ParcaCikisEmriId")), string.Empty))
                        dr["stCikisId"] = 1;

            bsCELines.EndEdit();
        }

        void CikilmadiA(object sender, EventArgs e)
        {
            foreach (int handle in gv.GetSelectedRows())
                if (intParse(gv.GetRowCellValue(handle, "stGenelId")) < 2)
                    foreach (DataRow dr in gvLines.DataTable().Select("ParcaCikisEmriId=" + strParse(gv.GetRowCellValue(handle, "ParcaCikisEmriId")), string.Empty))
                        dr["stCikisId"] = 2;

            bsCELines.EndEdit();
        }

        void Cikildi(object sender, EventArgs e)
        {
            if (intParse(bsCE, "stGenelId") < 2)
                foreach (int handle in gvLines.GetSelectedRows())
                    gvLines.SetRowCellValue(handle, "stCikisId", 1);

            bsCELines.EndEdit();
        }

        void Cikilmadi(object sender, EventArgs e)
        {
            if (intParse(bsCE, "stGenelId") < 2)
                foreach (int handle in gvLines.GetSelectedRows())
                    gvLines.SetRowCellValue(handle, "stCikisId", 2);

            bsCELines.EndEdit();
        }


        private void gvCikisEmirleri_FocusedRowChanged(object sender, DevExpress.XtraGrid.Views.Base.FocusedRowChangedEventArgs e)
        {
            if (bsCE != null && bsCE.Current != null)
            {
                bsiHeader.Caption = ((DataRowView)bsCE.Current).Row["ParcaCikisEmriId"].ToString();
                gvLines.BestFitColumns();
            }
        }

        private string GetParcaCikisEmriId(string idxs)
        {
            foreach (int rowHandle in gv.GetSelectedRows())
                if (rowHandle > -1)
                    idxs += gv.GetRowCellValue(rowHandle, "ParcaCikisEmriId").ToString() + ",";

            if (idxs.Substring(idxs.Length - 1, 1) == ",")
                idxs = idxs.Substring(0, idxs.Length - 1);
            return idxs;
        }

        void PrintOrtakKumas(object sender, EventArgs e)
        {
            int ParcaCikisEmriId = intParse(gv.GetRowCellValue(gv.FocusedRowHandle, "ParcaCikisEmriId"));
            Rapor.xrIrsaliyeOrtak ortak = new Rapor.xrIrsaliyeOrtak(ParcaCikisEmriId);
            ortak.PrinterName = "Xerox Plaser 6180n Pcl6";
            ortak.ShowPreview();
        }

        void ParcaEtiketiBas(object sender, EventArgs e)
        {
            string ParcaCikisEmriIds = string.Empty;
            ParcaCikisEmriIds = GetParcaCikisEmriId(ParcaCikisEmriIds);
            using (ParcaCikisEtiketiBas pe = new ParcaCikisEtiketiBas(ParcaCikisEmriIds))
                pe.ShowDialog();
        }

        void PrintShip(object sender, EventArgs e)
        {
            string ParcaCikisEmriIds = string.Empty;
            ParcaCikisEmriIds = GetParcaCikisEmriId(ParcaCikisEmriIds);
            using (KumasIrsaliyeOlustur ki = new KumasIrsaliyeOlustur(ParcaCikisEmriIds, 'P'))
                ki.ShowDialog();
        }

        void PrintRollCut(object sender, EventArgs e)
        {
            string ParcaCikisEmriIds = string.Empty;
            ParcaCikisEmriIds = GetParcaCikisEmriId(ParcaCikisEmriIds);
            Rapor.xrIrsaliye RollCut = new Rapor.xrIrsaliye(ParcaCikisEmriIds, 1, "GetParcaCikisEmri");
            RollCut.PrintingSystem.EndPrint += new EventHandler(PrintingSystem_EndPrint);
            RollCut.ShowPreview();
        }

        void PrintingSystem_EndPrint(object sender, EventArgs e)
        {
            string ParcaCikisEmriIds = string.Empty;
            ParcaCikisEmriIds = GetParcaCikisEmriId(ParcaCikisEmriIds);
            ExecuteNonQuery("UpdIsParcaCekiPrinted", ParcaCikisEmriIds);
            Yenile();
        }

        void gvCikisEmirleri_RowStyle(object sender, DevExpress.XtraGrid.Views.Grid.RowStyleEventArgs e)
        {
            int currentStGenelId = intParse(gv.GetRowCellValue(e.RowHandle, "stGenelId"));

            if (currentStGenelId != 0)
            {
                if (currentStGenelId == 3)
                {
                    e.Appearance.Font = new Font(AppearanceObject.DefaultFont, FontStyle.Strikeout);
                    e.Appearance.ForeColor = Color.Gray;
                }
                else if (currentStGenelId == 2)
                {
                    e.Appearance.ForeColor = Color.Gray;
                }
                else if (boolParse(gv.GetRowCellValue(e.RowHandle, "ToCut")))
                {
                    e.Appearance.ForeColor = Color.OrangeRed;
                }
            }
        }


        void IptalEt(object sender, EventArgs e)
        {
            int stGenelId = Convert.ToInt32(gv.GetFocusedRowCellValue("stGenelId"));
            if (stGenelId == 2)
            {
                ShowInfoMessage("Kapatılmış olan parça çıkış emrini iptal edemezsiniz !");
                return;
            }
            if (ParcaCikisEmriId != -1)
            {
                using (CikisEmriIptal cikisIptal = new CikisEmriIptal())
                    if (cikisIptal.ShowDialog() == DialogResult.OK)
                    {
                        ExecuteNonQuery("CancelParcaCikisEmri", ParcaCikisEmriId, cikisIptal.Notes, WhoAmI);
                        Yenile();
                    }
            }
            else
            {
                ShowInfoMessage("Lütfen önce parça çıkış emri satırı seçiniz.");
            }
        }

        private void ToplarinYeriniGoster(object sender, EventArgs e)
        {
            if (ParcaCikisEmriId != -1)
            {
                using (ToplarinYeri toplarinYeri = new ToplarinYeri(ParcaCikisEmriId))
                    toplarinYeri.ShowDialog();
            }
            else
            {
                ShowInfoMessage("Lütfen önce parça çıkış emri seçiniz.");
            }
        }

        private void CreateVerticalGrid()
        {
            DataTable dt = AppSession.Lookups.HareketTipi.Select("HareketTipiId in (22,23)").CopyToDataTable();
            RepositoryItemGridLookUpEdit riCikisTipi = GetCustomGLE(dt, "Name", "HareketTipiId");

            vgc.Rows.AddRange(new BaseRow[] {
                AddItem("Durum", typeof(string), riGenel),
                AddItem("CikisTipiId", typeof(int), riCikisTipi),
                AddItem("ParcaCikisEmriId", typeof(int)),
                AddItem("AtelyeId", typeof(int), RI(Rp.Atelye)),
                AddItem("CustomerId", typeof(int), RI(Rp.V_Customer)),
                AddItem("VendorId", typeof(int), RI(Rp.Vendor)),
                AddItem("BrandId", typeof(int), RI(Rp.Brand)),
                AddItem("OlusturulmaTarihi", typeof(DateTime), new RepositoryItemDateEdit()),
                AddItem("CikisTarihi", typeof(DateTime), new RepositoryItemDateEdit()),
                AddItem("Notes", typeof(string), new RepositoryItemMemoEdit()),
                AddItem("isCekiPrinted", typeof(bool)),
                AddItem("ProductId", typeof(int), RI(Rp.V_Kumas)),
                AddItem("RollId", typeof(int)),
                AddItem("stCikisId", typeof(int), RI(Rp.stCikis))
            });

            vgc.Rows.GetRowByFieldName("Notes", true).Height = 60;
            //, GetCustomRI("AG", true, "A", "G", "Tümü")

            vgc.OptionsBehavior.UseEnterAsTab = true;
            vgc.LayoutStyle = DevExpress.XtraVerticalGrid.LayoutViewStyle.SingleRecordView;
            vgc.CustomDrawRowHeaderCell += new CustomDrawRowHeaderCellEventHandler(vgc_CustomDrawRowHeaderCell);
            vgc.Appearance.RowHeaderPanel.BackColor = Color.LightBlue;

            //            vgc.RecordWidth = splitContainerControl2.Panel1.Width - vgc.RowHeaderWidth - 3;

            vgc.SetCellValue(vgc.Rows["Durum"], 0, "AÇIK");
            vgc.FocusedRow = vgc.Rows["ParcaCikisEmriId"];
            vgc.BestFit();
        }

        public BaseRow AddItem(string name, Type t, params RepositoryItem[] ri)
        {
            return AddItem(vgc, name, t, ri);
        }

        object GetVal(string FieldName)
        {
            return vgc.GetCellValue(vgc.Rows[FieldName], vgc.FocusedRecord);
        }

        void btnGetir_Click(object sender, EventArgs e)
        {
            Yenile();
        }

        private void Yenile()
        {
            gv.RefreshDataSource(true, "GetParcaCikisEmriFiltered",
                strParse(GetVal("Durum")),
                intParse(GetVal("CikisTipiId")),
                intParse(GetVal("ParcaCikisEmriId")),
                intParse(GetVal("AtelyeId")),
                intParse(GetVal("CustomerId")),
                datetimeParse(GetVal("OlusturulmaTarihi")),
                datetimeParse(GetVal("CikisTarihi")),
                strParse(GetVal("Notes")),
                boolParse(GetVal("isCekiPrinted")),
                intParse(GetVal("ProductId")),
                intParse(GetVal("RollId")),
                intParse(GetVal("stCikisId"))
                );

            gvLines.FocusedRowHandle = gvLines.LocateByDisplayText(0, gvLines.Columns["Hit"], "1");
            //gvCELines2.FocusedRowHandle = gvCELines2.LocateByDisplayText(0, gvCELines2.Columns["Hit"], "1");

            gv.BestFitColumns();
            gvLines.BestFitColumns();

            Notify("Done.");
        }

        void btnTemizle_Click(object sender, EventArgs e)
        {
            foreach (BaseRow r in vgc.Rows)
                vgc.SetCellValue(r, 0, null);
        }
    }
}
